package com.sun.mvc.controller;

import com.sun.mvc.bean.Employee;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

// HttpMessageConverter学习 @RequestBody RequestEntity  @ResponseBody ResponseEntity
@Controller
public class HttpMessageConverterController {

    //1、@RequestBody
    @RequestMapping(value = "/testRequestBody")
    public String testRequestBody(@RequestBody String requestBody) throws UnsupportedEncodingException {
        System.out.println("requestBody = " + URLDecoder.decode(requestBody, "UTF-8"));
        return "success";
    }

    //2、RequestEntity
    @RequestMapping("/testRequestEntity")
    public String testRequestEntity(RequestEntity<String> requestEntity) throws UnsupportedEncodingException {
        System.out.println("requestHeader:"+requestEntity.getHeaders());
        System.out.println("requestBody:"+ URLDecoder.decode(requestEntity.getBody(),"UTF-8"));
        return "success";
    }

    // 使用原始的Response对象向浏览器响应数据
    @RequestMapping(value = "/testResponseBody_test")
    public void testResponseBody_test(HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print("你好");
    }

    //3、@ResponseBody
    @RequestMapping("/testResponseBody")
    @ResponseBody
    public String testResponseBody(){
        return "success中文";
    }

    //4、SpringMVC处理json
    @RequestMapping("/testResponseBody1")
    @ResponseBody
    public Employee testResponseBody1(){
        return new Employee(1001, "孙鸿广", "aa@163.com", 1);
    }

    @RequestMapping("/testResponseBody2")
    @ResponseBody
    public ResponseEntity<Employee> testResponseBody2(){
        ResponseEntity<Employee> responseEntity = new ResponseEntity<>(new Employee(1001, "孙鸿广", "aa@163.com", 1), HttpStatus.OK);
        return responseEntity;
    }

    //5、SpringMVC处理ajax
    @RequestMapping("/testAxios")
    @ResponseBody
    public String testAjax(String username, String password){
        System.out.println("username:"+username+",password:"+password);
        return "hello,ajax";
    }
}
